package com.example.service;

import com.example.common.JwtTokenUtils;
import com.example.dao.AdminDao;
import com.example.entity.Admin;
import com.example.entity.Params;
import com.example.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 日期：2025/5/11 19:57
 */

@Service
public class AdminService {

    @Resource
    private AdminDao adminDao;

    public List<Admin> findAll() {
        return adminDao.selectAll();
    }

    public PageInfo<Admin> findBySearch(Params params) {
//        开启分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
//        接下来的查询会自动按照当前开启的分页设置来查询
        List<Admin> list = adminDao.findBySearch(params);
        return PageInfo.of(list);
    }

    public void add(Admin admin) {
        if(admin.getName() == null || admin.getName().trim().equals("")){
            throw new CustomException("用户名不能为空");
        }
        Admin user = adminDao.findByName(admin.getName());
        if(user != null) {
            throw new CustomException("用户名已存在,请勿更换用户名");
        }
        if(admin.getPassword() == null){
            admin.setPassword("123456");
        }
        adminDao.insertSelective(admin);
    }

    public void update(Admin admin) {
        adminDao.updateByPrimaryKeySelective(admin);
    }

    public void delete(Integer id) {
        adminDao.deleteByPrimaryKey(id);
    }


    public Admin login(Admin admin) {
        if(admin.getName() == null || "".equals(admin.getName())){
            throw new CustomException("用户名不能为空");
        }
        if(admin.getPassword() == null ||  "".equals(admin.getPassword())){
            throw new CustomException("密码不能为空");
        }
        Admin user = adminDao.findByNameAndPassword(admin.getName(), admin.getPassword());
        if(user == null){
            throw new CustomException("用户名或密码错误");
        }
//        生成登录用户的token
        String token = JwtTokenUtils.genToken(user.getId().toString(), user.getPassword());
        user.setToken(token);
        return user;
    }

//    根据主键查询id信息
    public Admin findByById(Integer id) {
        return adminDao.selectByPrimaryKey(id);
    }

}
